import tkinter
import requests
import subprocess
from urllib.request import quote
import os
import tkinter.messagebox

headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36",
}

root = tkinter.Tk()
root.title('vro2TK')
root.geometry('600x160+600+300')
root.iconbitmap('./q.ico')


# photo=tkinter.PhotoImage(file=".\\aa.png")
# tkinter.Label(root, image=photo).grid(row=0,column=0)

def c():
    print(charactor_number.get())


charactor_number = tkinter.IntVar()
tkinter.Radiobutton(root, text='音街', variable=charactor_number, value=2004).grid(row=0, column=0)
# tkinter.Radiobutton(root, text='屑星灯2', variable=charactor_number, value=554 ).grid(row=0,column=1)
# tkinter.Radiobutton(root, text='屑星灯3', variable=charactor_number, value=554 ).grid(row=0,column=2)
l1 = tkinter.Label(root, text='入力：', font=(25))
l1.grid(row=1, column=0)
my_mess = tkinter.StringVar()
mess_area = tkinter.Entry(root, width=50, textvariable=my_mess, font=(25))
mess_area.grid(row=1, column=1)


def catch_and_conversion_audio():
    to_hanashi_name = catch_audio()
    conversion_audio(to_hanashi_name)
    delete_ogg(to_hanashi_name)
    tkinter.messagebox.showinfo('取得完了', to_hanashi_name)

    return


def delete_ogg(file_name):
    remove_path = get_file_align() + file_name + '.ogg'
    # print(remove_path)
    os.remove(remove_path)


def catch_audio():
    hanashi = mess_area.get()
    ret1 = quote(hanashi, safe=";/?:@&=+$,", encoding="utf-8")
    # print(ret1)
    url1 = 'https://cloud.ai-j.jp/demo/aitalk2webapi_nop.php?callback=callback&speaker_id=' + str(
        get_charactor()) + '&text='

    fina_request = url1 + ret1 + get_para()
    print(fina_request)

    nama_response = requests.get(fina_request, headers=headers)
    nama_response_text = nama_response.text
    tlist = nama_response_text.split('\\')
    ture_target = 'http://' + tlist[2][1:] + tlist[3] + tlist[4] + tlist[5][:-3]
    # print(ture_target)

    audio_save_des = get_file_align() + hanashi + '.ogg'
    audio_data = requests.get(ture_target, headers=headers)
    with open(audio_save_des, "wb+") as temp_file:
        temp_file.write(audio_data.content)

    return hanashi


def conversion_audio(file_name):
    cmd_com = 'ffmpeg -i ' + get_file_align() + file_name + '.ogg -acodec libmp3lame ' + get_file_align() + file_name + '.mp3'
    subprocess.call(cmd_com)
    # print(cmd_com)
    # print(file_name+'\n')


def get_charactor():
    return charactor_number.get()


def get_para():
    return '&ext=ogg&volume=1.0&speed=1.0&pitch=1.0'


def get_file_align():
    return 'D:\\pachong\\'


bu1 = tkinter.Button(root, text='CLick', command=catch_and_conversion_audio)
bu1.grid(row=2, column=1)

root.mainloop()
